-module(prime_server).
-behaviour(gen_server).
-compile(export_all).

%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
	 terminate/2, code_change/3]).
	 
start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

new_prime(N) ->
    gen_server:call(?MODULE, {prime, N}, 20000).

init([]) -> 
    process_flag(trap_exit, true),
    io:format("~p starting~n", [?MODULE]),
    {ok, 0}.

handle_call({prime, K}, _From, N) ->
    {reply, make_new_prime(K), N+1}.

handle_cast(_Msg, State) -> {noreply, State}.
handle_info(_Info, State) -> {noreply, State}.
terminate(_Reason, _State) -> 
    io:fwrite("~p stopping~n", [?MODULE]),
    ok.
	
code_change(_OldVsn, State, _Extra) -> {ok, State}.

make_new_prime(K) ->
    if
        K > 100 ->
            alarm_handler:set_alarm(tooHot),
            N = lib_primes:make_prime(K),
            alarm_handler:clear_alarm(tooHot),
            N;
        true ->
            lib_primes:make_prime(K)
    end.
			